import request from '@/utils/request.js'

// 获取用户可用优惠券列表
export function getAvailableCoupons(userId, params = {}) {
  return request({
    url: `api/coupons/getCoupons`,
    method: 'GET',
    params: {
      id: userId,
      status: 1, // 1: 未使用, 2: 已使用, 3: 已过期
      ...params
    }
  })
}

// 获取用户所有优惠券
export function getUserCoupons(userId) {
  return request({
    url: `api/coupons/getCoupons`,
    method: 'GET',
    params: { id: userId }
  })
}

// 检查优惠券是否可用
export function checkCouponAvailable(couponId, orderAmount) {
  return request({
    url: `api/coupons/check`,
    method: 'POST',
    data: {
      couponId,
      orderAmount
    }
  })
}

// 使用优惠券
export function useCoupon(couponId, orderId) {
  return request({
    url: `api/coupons/use`,
    method: 'POST',
    data: {
      couponId,
      orderId
    }
  })
}

// 计算优惠券折扣金额
export function calculateDiscount(coupon, orderAmount) {
  if (!coupon || orderAmount < coupon.minSpend) {
    return 0
  }
  
  if (coupon.type === 1) {
    // 满减券
    return Math.min(coupon.amount, orderAmount)
  } else if (coupon.type === 2) {
    // 折扣券 (amount 为折扣，如 85 表示 8.5 折)
    const discount = (100 - coupon.amount) / 100
    return orderAmount * discount
  }
  
  return 0
}

// 导出couponApi对象
export const couponApi = {
  getAvailableCoupons,
  getUserCoupons,
  checkCouponAvailable,
  useCoupon,
  calculateDiscount
}
